package com.ahui.mallchat.common.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ahui.mallchat.common.common.constant.MQConstant;
import com.ahui.mallchat.common.common.constant.RedisKey;
import com.ahui.mallchat.common.common.domain.dto.ScanSuccessMessageDTO;
import com.ahui.mallchat.common.common.utils.RedisUtils;
import com.ahui.mallchat.common.user.dao.UserDao;
import com.ahui.mallchat.common.user.domain.entity.User;
import com.ahui.mallchat.common.user.service.UserService;
import com.ahui.mallchat.common.user.service.WXMsgService;
import com.ahui.mallchat.common.user.service.adapter.TextBuilder;
import com.ahui.mallchat.common.user.service.adapter.UserAdapter;
import com.ahui.mallchat.common.websocket.service.WebSocketService;
import com.ahui.mallchat.transaction.service.MQProducer;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * Author:ahui
 * Description:
 * Date: 2024/7/21 13:01
 */
@Service
@Slf4j
public class WXMsgServiceImpl implements WXMsgService {

    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    @Lazy
    private WxMpService wxMpService;

    @Value("${wx.mp.callback}")
    private String callback;

    @Autowired
    private MQProducer mqProducer;

    /**
     * openid和登录code的关系map
     */
     private static final ConcurrentHashMap<String,Integer> WAIT_AUTHORIZE_MAP = new ConcurrentHashMap<>();

    public static final String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";


    @Override
    public WxMpXmlOutMessage scan(WxMpService wxMpService, WxMpXmlMessage wxMpXmlMessage) {
        String openId = wxMpXmlMessage.getFromUser();
        Integer code = getEvenKey(wxMpXmlMessage);
        if (Objects.isNull(code)){
            return null;
        }
        User user = userDao.getByOpenId(openId);
        boolean registered = Objects.nonNull(user);
        boolean authorized = registered && StrUtil.isNotBlank(user.getAvatar());
        //用户已经注册并授权
        if (registered && authorized){
            //走登录成功逻辑 通过code找到给channel推送消息
            webSocketService.scanLoginSuccess(code,user.getId());
            return null;
        }
        //用户未注册，就先注册的逻辑
        if (!registered){
            User insert = UserAdapter.buildUserSave(openId);
            userService.register(insert);
        }
        //在redis中保存openid和场景code的关系，后续才能通知到前端,旧版数据没有清除,这里设置了过期时间
        RedisUtils.set(RedisKey.getKey(RedisKey.OPEN_ID_STRING, openId), code, 60, TimeUnit.MINUTES);
        //授权流程,给用户发送授权消息，并且异步通知前端扫码成功,等待授权
        mqProducer.sendMsg(MQConstant.SCAN_MSG_TOPIC, new ScanSuccessMessageDTO(code));
        String skipUrl = String.format(URL, wxMpService.getWxMpConfigStorage().getAppId(), URLEncoder.encode(callback + "/wx/portal/public/callBack"));
        WxMpXmlOutMessage.TEXT().build();
        return new TextBuilder().build("请点击链接授权：<a href=\"" + skipUrl + "\">登录</a>", wxMpXmlMessage, wxMpService);
    }

    @Override
    public void authorize(WxOAuth2UserInfo userInfo) {
        String openid = userInfo.getOpenid();
        User user = userDao.getByOpenId(openid);
        //更新用户信息
        if (StrUtil.isBlank(user.getAvatar())){
            fillUserInfo(user.getId(),userInfo);
        }
        //通过code找到用户channel,进行登录
        Integer code = WAIT_AUTHORIZE_MAP.remove(openid);
        webSocketService.scanLoginSuccess(code,user.getId());
    }


    private void fillUserInfo(Long uid, WxOAuth2UserInfo userInfo) {
        String newNickname = userInfo.getNickname();
        User existingUser = userDao.getByNickname(newNickname);

        // 检查是否有同名的用户已经存在，并且不是当前用户
        while (existingUser != null && !existingUser.getId().equals(uid)) {
            // 生成随机的后缀
            String randomSuffix = RandomStringUtils.randomNumeric(4);
            newNickname = userInfo.getNickname() + "_" + randomSuffix;

            // 再次检查新昵称是否已存在
            existingUser = userDao.getByNickname(newNickname);
        }

        // 构建要更新的用户信息
        User user = UserAdapter.buildAuthorizeUser(uid, userInfo);
        user.setName(newNickname);

        // 更新数据库中的用户信息
        userDao.updateById(user);

        // 日志记录
        log.info("User info updated for user ID: {}, new nickname: {}", uid, newNickname);
    }




    private Integer getEvenKey(WxMpXmlMessage wxMpXmlMessage) {
        try {
            String eventKey = wxMpXmlMessage.getEventKey();
            String code = eventKey.replace("qrscene_", "");
            return Integer.parseInt(code);
        }catch (Exception e){
            log.error("getEventKey error eventKey:{}",wxMpXmlMessage.getEventKey(),e);
            return null;
        }
    }
}
